import { Pagination, PaginationProps } from 'antd'
import React, { useImperativeHandle, useState } from 'react'
import {
  PaginationComponetProps,
  PaginationComponetPropsPartial,
} from '@/types'

/**
 * 分页实例
 */
export interface BasicPaginationRef {
  /**
   * 当前页码
   */
  pageNumber: number
  /**
   * 每页条数
   */
  pageSize: number
  /**
   * 分页器信息
   */
  pagination: PaginationComponetProps
  /**
   * 设置分页
   * @param pagination 分页
   */
  setPagination: (pagination: PaginationComponetPropsPartial) => void
}

/**
 * 分页器属性
 */
export interface BasicPaginationProps extends PaginationProps {
  /**
   * 分页器实例
   */
  ref?: React.RefObject<BasicPaginationRef>
}

/**
 * 标准分页器组件
 */
export const BasicPagination = (props: BasicPaginationProps) => {
  const [pagination, _setPagination] = useState<PaginationComponetProps>({
    pageNumber: 1,
    pageSize: 10,
    total: 0,
  })

  const { ref, ...restProps } = props

  useImperativeHandle(ref, () => ({
    pagination,
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    setPagination: (k) => _setPagination((item) => ({ ...item, ...k })),
  }))

  return (
    <Pagination
      showTotal={(total) => `总 ${total} 条`}
      {...restProps}
      current={pagination.pageNumber}
      pageSize={pagination.pageSize}
      total={pagination.total}
    />
  )
}
